package TestPaperSystem.service.impl;

import TestPaperSystem.Dto.UserLoginDto;
import TestPaperSystem.Dto.UserVO;
import TestPaperSystem.config.product.Product;
import TestPaperSystem.entity.User;
import TestPaperSystem.mapper.UserMapper;
import TestPaperSystem.service.RoleService;
import TestPaperSystem.service.UserService;
import TestPaperSystem.utils.DateGetter;
import TestPaperSystem.utils.MD5Utils;
import TestPaperSystem.utils.RedisUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xwj
 * @since 2023-03-25
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    UserMapper userMapper;

    @Autowired
    RoleService roleService;

    @Autowired
    Product product;

    @Override
    public UserLoginDto saveUser(UserVO user) throws Exception{
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        List<User> lists = userMapper.selectList(userQueryWrapper.eq("user_name",user.getUserName()));
        String token = java.util.UUID.randomUUID().toString().replace("-", "");
        String salt = token.substring(0,6);
        String code = (String)RedisUtils.redis.opsForValue().get("code" + user.getUserName());

        if(code == null){
            throw new Exception("验证码已过期");
        }
        if(!code.equals(user.getCaptchaValue()))
            throw new Exception("验证码错误");
        if(lists.isEmpty()){
            UserLoginDto dto = new UserLoginDto();
            user.setCreateTime(DateGetter.getInstance().getCurrentTime());
            user.setUpdateTime(DateGetter.getInstance().getCurrentTime());
            String password = MD5Utils.inputPassToDBPass(user.getPassword(),salt);
            user.setSalt(salt);
            user.setPassword(password);

            this.save(user);

            User user_db = userMapper.selectOne(userQueryWrapper.eq("user_name",user.getUserName()));

            dto.setRoles(roleService.getRolesByUserName(user.getUserName()));
            dto.setToken(token);
            BeanUtils.copyProperties(user_db,dto);
            RedisUtils.redis.opsForValue().set(token,dto,30 , TimeUnit.MINUTES);

            return dto;
        }
        else
            throw new Exception("该邮箱已被使用");

    }

    @Override
    public UserLoginDto getUser(User user) throws Exception {
        UserLoginDto dto = new UserLoginDto();
         User userDb = this.getOne(new QueryWrapper<User>()
                .eq("user_name",user.getUserName()));
         if(userDb == null){
             throw new Exception("没有找到此用户");
         }else if(!userDb.getPassword().equals(MD5Utils.inputPassToDBPass(user.getPassword(),userDb.getSalt()))){
             throw new Exception("密码错误");
         }else{
             BeanUtils.copyProperties(userDb,dto);

             dto.setRoles(roleService.getRolesByUserName(user.getUserName()));
             String token = java.util.UUID.randomUUID().toString().replace("-", "");
             dto.setToken(token);

             RedisUtils.redis.opsForValue().set(token,dto,30 , TimeUnit.MINUTES);

             return dto;
         }

    }

    @Override
    public boolean getCode(String email) {
        try{
            product.sendMessage("sendRegister",email);
        }catch (Exception e){
            return false;
        }

        return true;
    }

    @Override
    public UserLoginDto updateUserPass(UserVO resetForm) throws Exception {
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        List<User> lists = userMapper.selectList(userQueryWrapper.eq("user_name",resetForm.getUserName()));
        String token = java.util.UUID.randomUUID().toString().replace("-", "");
        String salt = token.substring(0,6);
        String code = (String)RedisUtils.redis.opsForValue().get("code" + resetForm.getUserName());

        if(code == null)
            throw new Exception("验证码已过期");
        if(!code.equals(resetForm.getCaptchaValue()))
            throw new Exception("验证码错误");
        if(lists.isEmpty())
            throw new Exception("未找到该用户");
        UpdateWrapper<User> updateWrapper = new UpdateWrapper<User>();

        boolean update = this.update(null,updateWrapper
                .lambda()
                .set(StringUtils.isNotBlank(resetForm.getPassword()), User::getPassword, MD5Utils.inputPassToDBPass(resetForm.getPassword(), salt))
                .set(User::getSalt,salt)
                .eq(StringUtils.isNotBlank(resetForm.getUserName()), User::getUserName, resetForm.getUserName()));
        if(!update){
            throw new Exception("更新失败,系统出现错误");
        }

        return this.getUser(resetForm);

    }

}
